import { useMemo } from "react";
import {
  Navigate,
  RouteObject,
  matchRoutes,
  useLocation,
  renderMatches,
} from "react-router-dom";
import Layout from "../layout";
import { useCommonStore } from "../store";
import { Menus, MyRouteObject } from "../store/common";
import Page from "./page";
import routeRequest from "./request";

// 导入pages下的所有主页面,用于根据路径匹配网络请求菜单对应的组件
const comp: any = import.meta.glob("../pages/**/index.tsx", { eager: true });

// 处理网络请求菜单的方法
const formatterRouter = (menus: Menus | RouteObject[]) => {
  // 根据接口返回数据动态导入组件
  const replaceElement = (route: MyRouteObject | RouteObject) => {
    // 匹配路径
    const fitPath: any = Object.keys(comp).find((item: string) =>
      item.replace(/(\/index\.tsx)$/, "").endsWith(route.element as string)
    );
    // 得到匹配路径组件信息
    const Component = comp[fitPath]?.default || Page.NoFind;
    route.element = (
      <Layout>
        <Component />
      </Layout>
    );
  };

  // 递归处理菜单方法
  const recursion = (routes: Menus | RouteObject[]) => {
    // 循环遍历请求得到的菜单
    routes?.forEach((fRoute) => {
      if (fRoute.element) replaceElement(fRoute);
      if (fRoute.children) recursion(fRoute.children);
    });
  };

  recursion(menus);

  return menus as RouteObject[];
};

export default () => {
  const { menus, setMenus } = useCommonStore();
  const location = useLocation();

  // 获取菜单信息并存储在仓库中
  const initMenus = async () => {
    const menuList: any = await routeRequest();
    setMenus(menuList);
  };

  // 判断菜单不存在的时候请求菜单数据
  if (!menus) initMenus();

  // 最终展示的路由配置
  const routes: RouteObject[] = useMemo(
    () => [
      {
        path: "/",
        element: <Navigate to="/login" />,
      },

      {
        path: "/login",
        element: <Page.Login />,
      },
      ...(formatterRouter(menus) || []),
      {
        path: "*",
        element: <Page.NoFind />,
      },
    ],
    [menus]
  );

  // 匹配当前的路由
  const matchRoute = useMemo(
    () => matchRoutes(routes, location),
    [location.pathname, routes]
  );

  if (!menus?.length && location.pathname !== "/login")
    return <div style={{ textAlign: "center" }}>页面加载中...</div>;

  return renderMatches(matchRoute);
};
